package com.example.spring_trans.controller;

import com.example.spring_trans.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Li_yizYa
 * Date: 2025/7/25
 * Time: 13:31
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    // 编程式事务
    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;

    @Autowired
    private TransactionDefinition transactionDefinition;

    @RequestMapping("/registry")
    public String registry(String name, String password) {
        // 用户注册
        // 开启事务
        // 拿到数据库执行之前的状态
        TransactionStatus transaction = dataSourceTransactionManager.getTransaction(transactionDefinition);
        userService.registryUser(name, password);
        // 提交事务, 修改生效
//        dataSourceTransactionManager.commit(transaction);
        // 回滚事务
        dataSourceTransactionManager.rollback(transaction);
        return "注册成功";
    }
}
